package com.seeyon.apps.brwh.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.brwh.kit.*;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.cap4.form.bean.FormTableBean;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.AppContext;
import com.seeyon.ctp.common.affair.manager.AffairManager;
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.log.CtpLogFactory;
import com.seeyon.ctp.common.po.affair.CtpAffair;
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem;
import com.seeyon.ctp.organization.bo.V3xOrgDepartment;
import com.seeyon.ctp.organization.bo.V3xOrgEntity;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.organization.manager.OrgManager;
import org.apache.commons.logging.Log;
import www.seeyon.com.utils.UUIDUtil;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 接收销售订单处理逻辑
 */
public class ReceptionSalesOrderService {
    private static final Log log = CtpLogFactory.getLog(ReceptionSalesOrderService.class);
    private static final String sapOrderUrl = AppContext.getSystemProperty("brwh.sapOrderUrl");
    private EnumManager enumManagerNew = (EnumManager) AppContext.getBean("enumManagerNew");
    private AffairManager affairManager = (AffairManager)AppContext.getBean("affairManager");
    private OrgManager orgManager = (OrgManager)AppContext.getBean("orgManager");

    private static CAP4FormManager cap4FormManager = (CAP4FormManager) AppContext.getBean("cap4FormManager");

    private static final String YGC_LSH_QZ = AppContext.getSystemProperty("brwh.ygcLshQz");

    private static final String XSDDDA_temp = AppContext.getSystemProperty("brwh.xsdddaTemp");

    //合同档案表模板编码
    private static final String XSHTDA_temp = AppContext.getSystemProperty("brwh.xshtdaTemp");

    //销售订单模板编码
    private static final String XSDD_TGDD_tempCode = AppContext.getSystemProperty("brwh.xsddTgddTempCode");


    /**
     * 处理接收到的销售订单数据
     * @param data
     * @throws Exception
     */
    public HashMap<String, Object> receptionSalesOrder(Map<String, Object> data){
        log.info("开始处理销售订单数据-------------------------");
        HashMap<String, Object> resulatMap = new HashMap<>();
        Boolean htJeIdentical = false;
        String uSalesContractNumber = StrKit.str(data.get("uSalesContractNumber"));
        if(uSalesContractNumber.equals("")){
            resulatMap.put("code","500");
            resulatMap.put("msg","合同编号不能为空！");
            resulatMap.put("data",null);
            return resulatMap;
        }
        try {
            htJeIdentical = isHtJeIdentical(data);
        } catch (Exception e) {
            log.error("根据合同数量判断合同金额异常", e);
            resulatMap.put("code","500");
            resulatMap.put("msg","根据合同数量判断合同金额异常");
            resulatMap.put("data",null);
            return resulatMap;
        }
        if(htJeIdentical){
            //直接推送SAP销售订单数据
            try {
                HashMap<String, Object> map = pushOrderSAP(data);
                if((Boolean)map.get("isPush")){
                    //保存销售订单档案表
                    Boolean aBoolean = saveSalesOrder(data, map);
                    if(aBoolean){
                        resulatMap.put("code","200");
                        resulatMap.put("msg","推送erp数据成功");
                        resulatMap.put("data",map);
                    }else{
                        resulatMap.put("code","500");
                        resulatMap.put("msg","保存销售订单数据到档案表中异常");
                        resulatMap.put("data",null);
                    }
                }else{
                    resulatMap = map;
                }
            } catch (Exception e) {
                log.error("阳光采销售订单推送ERP数据异常：",e);
                resulatMap.put("code","500");
                resulatMap.put("msg","阳光采销售订单推送ERP数据异常");
                resulatMap.put("data",null);
            }
        }else{
            //发起销售订单
            try {
                resulatMap = startFrom(data);
            } catch (BusinessException e) {
                log.error("阳光采销售订单发起OA流程表单异常：",e);
                resulatMap.put("code","500");
                resulatMap.put("msg","阳光采销售订单发起OA流程表单异常");
                resulatMap.put("data",null);
            }
        }
        return resulatMap;
    }


    /**
     * 获取合同档案数据进行判断是金额是否一致
     * @param data
     * @return
     */
    private Boolean isHtJeIdentical(Map<String, Object> data) throws Exception {
        //获取明细数据
        ArrayList<HashMap<String, Object>> subDataList = (ArrayList<HashMap<String, Object>>)data.get("mxdataList");
        if(subDataList.isEmpty()){
            return false;
        }
        String uSalesContractNumber = StrKit.str(data.get("uSalesContractNumber"));
        if("".equals(uSalesContractNumber)){
            return false;
        }
        log.info("获取到的销售合同编号为："+XSHTDA_temp);
        //获取合同档案表数据
        FormBean formByFormCode = cap4FormManager.getFormByFormCode(XSHTDA_temp);
        FormFieldBean htCodeFeildBean = formByFormCode.getFieldBeanByDisplay("合同编号");
        FormFieldBean isTDFeildBean = formByFormCode.getFieldBeanByDisplay("是否梯度价格");

        //获取非阶梯价的字段
        FormFieldBean cpbmFeildBean = formByFormCode.getFieldBeanByDisplay("产品编码-销售清单");
        FormFieldBean htslFeildBean = formByFormCode.getFieldBeanByDisplay("合同数量-销售清单");
        FormFieldBean hsdjFeildBean = formByFormCode.getFieldBeanByDisplay("含税单价-销售清单");
        FormFieldBean ggxhFeildBean = formByFormCode.getFieldBeanByDisplay("规格型号-销售清单");

        //阶梯价字段
        FormFieldBean cpbmJtjFeildBean = formByFormCode.getFieldBeanByDisplay("产品编码-销售清单阶梯价");
        FormFieldBean slfwJtjFeildBean = formByFormCode.getFieldBeanByDisplay("合同范围数量-销售清单阶梯价");
        FormFieldBean hsdjJtjFeildBean = formByFormCode.getFieldBeanByDisplay("含税单价-销售清单阶梯价");
        FormFieldBean ggxhJtjFeildBean = formByFormCode.getFieldBeanByDisplay("规格型号-销售清单阶梯价");

        FormTableBean masterTableBean = formByFormCode.getMasterTableBean();
        String tableName = masterTableBean.getTableName();
        //获取合同数据
        String htSql = "select id,"+isTDFeildBean.getName()+" from "+tableName+" where "+htCodeFeildBean.getName()+" = '"+uSalesContractNumber+"'";
        log.info("开始获取销售合同数据SQL："+htSql);
        List<Map<String, Object>> maps = DBKit.excuteSQL(htSql, null);
        if(maps.isEmpty()){
            return false;
        }else{
            //获取是否阶梯价
            String isTDPrice = StrKit.str(maps.get(0).get(isTDFeildBean.getName()));
            CtpEnumItem ctpEnumItem = enumManagerNew.getCtpEnumItem(Long.parseLong(isTDPrice));
            isTDPrice = ctpEnumItem.getShowvalue();

            data.put("isTDPrice",ctpEnumItem.getId());

            String masterId = StrKit.str(maps.get(0).get("id"));
            boolean isXt = false;
            if(isTDPrice.equals("是")){
                //阶梯价判断逻辑处理
                //获取明细表名称
                String ownerTableName = cpbmJtjFeildBean.getOwnerTableName();
                String subSql = "select "+cpbmJtjFeildBean.getName()+","+ggxhJtjFeildBean.getName()+","+slfwJtjFeildBean.getName()+","+hsdjJtjFeildBean.getName()+" from "+ ownerTableName + " where formmain_id = '" + masterId+"'";
                log.info("阳光采推送数据阶梯价明细表数据查询SQL："+subSql);
                List<Map<String, Object>> fromSubDataList = DBKit.excuteSQL(subSql, null);
                for (HashMap<String, Object> subDataMap : subDataList) {
                    String itemCode = StrKit.str(subDataMap.get("itemCode"));
                    String quantity = StrKit.str(subDataMap.get("quantity"));
                    double priceAfterVAT = Double.parseDouble(StrKit.str(subDataMap.get("priceAfterVAT")));
                    boolean isExist = false;
                    for (Map<String, Object> fomSubMap : fromSubDataList) {
                        String formItemCode = StrKit.str(fomSubMap.get(cpbmJtjFeildBean.getName()));
                        //规格型号
                        String ggxhJej = StrKit.str(fomSubMap.get(ggxhJtjFeildBean.getName()));
                        String slfwJtjValue = StrKit.str(fomSubMap.get(slfwJtjFeildBean.getName()));
                        String hsdjJtjValue = StrKit.str(fomSubMap.get(hsdjJtjFeildBean.getName()));
                        if(slfwJtjValue.equals("") || hsdjJtjValue.equals("")){
                            continue;
                        }
                        double v = Double.parseDouble(hsdjJtjValue);
                        if(formItemCode.equals(itemCode)){
                            Boolean numberInRange = Utils.isNumberInRange(Double.parseDouble(quantity), slfwJtjValue);
                            if(numberInRange){
                                if(priceAfterVAT == v){
                                    isExist = true;
                                }
                            }
                            subDataMap.put("specificationsModels",ggxhJej);
                        }
                    }
                    if(!isExist){
                        isXt = false;
                        break;
                    }else{
                        isXt = true;
                    }
                }
            }else{
                //非阶梯价判断逻辑处理
                //获取明细表名称
                String ownerTableName = cpbmFeildBean.getOwnerTableName();
                String subSql = "select "+cpbmFeildBean.getName()+","+ggxhFeildBean.getName()+","+htslFeildBean.getName()+","+hsdjFeildBean.getName()+" from "+ ownerTableName + " where formmain_id = '" + masterId+"'";
                List<Map<String, Object>> fromSubDataList = DBKit.excuteSQL(subSql, null);

                //产品数量和金额比对逻辑
                for (HashMap<String, Object> subDataMap : subDataList) {
                    String itemCode = StrKit.str(subDataMap.get("itemCode"));
                    String quantity = StrKit.str(subDataMap.get("quantity"));
                    double priceAfterVAT = Double.parseDouble(StrKit.str(subDataMap.get("priceAfterVAT")));
                    boolean isExist = false;
                    for (Map<String, Object> fomSubMap : fromSubDataList) {
                        String formItemCode = StrKit.str(fomSubMap.get(cpbmFeildBean.getName()));
                        //规格型号
                        String ggxh = StrKit.str(fomSubMap.get(ggxhFeildBean.getName()));
                        String slfwJtjValue = StrKit.str(fomSubMap.get(htslFeildBean.getName()));
                        String hsdjJtjValue = StrKit.str(fomSubMap.get(hsdjFeildBean.getName()));
                        if(slfwJtjValue.equals("") || hsdjJtjValue.equals("")){
                            continue;
                        }
                        double v = Double.parseDouble(hsdjJtjValue);
                        if(formItemCode.equals(itemCode)){
                            if(slfwJtjValue.equals(quantity)){
                                if(priceAfterVAT == v){
                                    isExist = true;
                                }
                            }
                            subDataMap.put("contractNumber",slfwJtjValue);
                            subDataMap.put("specificationsModels",ggxh);
                        }
                    }
                    if(!isExist){
                        isXt = false;
                        break;
                    }else{
                        isXt = true;
                    }
                }
            }
            return isXt;
        }
    }




    /**
     * 发起销售订单（团购订单）
     * @return
     */
    private HashMap<String, Object> startFrom(Map<String, Object> data) throws BusinessException {
        HashMap<String, Object> resulatMap = new HashMap<>();

        //获取填报人信息
        String uCreator = StrKit.str(data.get("uCreator"));
        if(!"".equals(uCreator)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(),
                    "code", uCreator, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uCreator = v3xOrgEntities.get(0).getId().toString();
            }
        }
        //填报部门
        String uDocumentDepartment = StrKit.str(data.get("uDocumentDepartment"));
        if(!"".equals(uDocumentDepartment)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgDepartment.class.getSimpleName(),
                    "code", uDocumentDepartment, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uDocumentDepartment = v3xOrgEntities.get(0).getId().toString();
            }
        }
        //填报单位
        String branchCode = StrKit.str(data.get("branchCode"));
        if(!"".equals(branchCode)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(branchCode);
            if(null != itemByCode){
                branchCode = itemByCode.getId().toString();
            }
        }
        //合同类型
        String contractType = StrKit.str(data.get("contractType"));
        if(!"".equals(contractType)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(contractType);
            if(null != itemByCode){
                contractType = itemByCode.getId().toString();
            }
        }
        //订单类型
        String uSalesOrderBusinessType = StrKit.str(data.get("uSalesOrderBusinessType"));
        if(!"".equals(uSalesOrderBusinessType)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(uSalesOrderBusinessType);
            if(null != itemByCode){
                uSalesOrderBusinessType = itemByCode.getId().toString();
            }
        }
        //销售订单类型
        String uSalesOrderType = StrKit.str(data.get("uSalesOrderType"));
        if(!"".equals(uSalesOrderType)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(uSalesOrderType);
            if(null != itemByCode){
                uSalesOrderType = itemByCode.getId().toString();
            }
        }

        //客户经理
        String uRY = StrKit.str(data.get("uRY"));
        if(!"".equals(uRY)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(),
                    "code", uRY, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uRY = v3xOrgEntities.get(0).getId().toString();
            }
        }
        //项目经理
        String uItem = StrKit.str(data.get("uItem"));
        if(!"".equals(uItem)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(),
                    "code", uItem, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uItem = v3xOrgEntities.get(0).getId().toString();
            }
        }
        //交付经理
        String uDelivery = StrKit.str(data.get("uDelivery"));
        if(!"".equals(uDelivery)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(),
                    "code", uDelivery, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uDelivery = v3xOrgEntities.get(0).getId().toString();
            }
        }
        //销售主体
        String salesEntity = StrKit.str(data.get("salesEntity"));
        if(!"".equals(salesEntity)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(salesEntity);
            if(null != itemByCode){
                salesEntity = itemByCode.getId().toString();
            }
        }
        //是否二次定制
        String isSC = StrKit.str(data.get("isSC"));
        if(!"".equals(isSC)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(isSC);
            if(null != itemByCode){
                isSC = itemByCode.getId().toString();
            }
        }
        //项目行业
        String itemIndustry = StrKit.str(data.get("itemIndustry"));
        if(!"".equals(itemIndustry)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(itemIndustry);
            if(null != itemByCode){
                itemIndustry = itemByCode.getId().toString();
            }
        }
        //选部门
        String uBM = StrKit.str(data.get("uBM"));
        if(!"".equals(uBM)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgDepartment.class.getSimpleName(),
                    "code", uBM, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uBM = v3xOrgEntities.get(0).getId().toString();
            }
        }
        //订单状态
        String orderStatus = StrKit.str(data.get("orderStatus"));
        if(!"".equals(orderStatus)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(orderStatus);
            if(null != itemByCode){
                orderStatus = itemByCode.getId().toString();
            }
        }

        //协作人
        String uSalesAssistancePersonnel = StrKit.str(data.get("uSalesAssistancePersonnel"));
        String xzrValue = "";
        if(!"".equals(uSalesAssistancePersonnel)){
            String[] split = uSalesAssistancePersonnel.split(",");
            for(int i = 0; i < split.length; i++) {
                List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(),
                        "code", split[i], null, false, true);
                if(!v3xOrgEntities.isEmpty()){
                    xzrValue += v3xOrgEntities.get(0).getId()+",";
                }
            }
            xzrValue = xzrValue.substring(0, xzrValue.length() - 1);
        }

        //是否例外场景
        String isLWCJ = StrKit.str(data.get("isLWCJ"));
        if(!"".equals(isLWCJ)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(isLWCJ);
            if(null != itemByCode){
                isLWCJ = itemByCode.getId().toString();
            }
        }

        //回款条件
        String uHKTJ = StrKit.str(data.get("uHKTJ"));
        if(!"".equals(uHKTJ)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(uHKTJ);
            if(null != itemByCode){
                uHKTJ = itemByCode.getId().toString();
            }
        }
        //获取枚举信息
        CtpEnumItem yEnum = enumManagerNew.getItemByCode("Y");


        FormBean formByFormCode = cap4FormManager.getFormByFormCode(XSDD_TGDD_tempCode);
        FormFieldBean ygclshFieldBean = formByFormCode.getFieldBeanByDisplay("阳光采流水号");
        FormFieldBean cpbmFieldBean = formByFormCode.getFieldBeanByDisplay("产品编码-订单明细");
        String masterTableName = ygclshFieldBean.getOwnerTableName();
        String subTableName = cpbmFieldBean.getOwnerTableName();

        //获取主表信息
        HashMap<Object, Object> formMasterData = new HashMap<>();
        formMasterData.put("阳光采流水号", StrKit.str(data.get("serialNumber")));
        formMasterData.put("填报人", uCreator);
        formMasterData.put("填报部门", uDocumentDepartment);
        formMasterData.put("填报日期", data.get("docDate"));
        formMasterData.put("填报单位", branchCode);
        formMasterData.put("合同名称", data.get("uSalesContractName"));
        formMasterData.put("合同编号", data.get("uSalesContractNumber"));
        formMasterData.put("项目名称", data.get("projectName"));
        formMasterData.put("项目编码", data.get("projectCode"));
        formMasterData.put("客户名称", data.get("cardName"));
        formMasterData.put("客户编码", data.get("cardCode"));
        formMasterData.put("合同类型", contractType);
        formMasterData.put("订单类型", uSalesOrderBusinessType);
        formMasterData.put("计划交货日期", data.get("docDueDate"));
        formMasterData.put("订单金额", data.get("orderPrice"));
        formMasterData.put("金额大写", data.get("UOrderPrice"));
        formMasterData.put("订单说明", data.get("comments"));
        formMasterData.put("关联报价单", data.get("glbjd"));
        formMasterData.put("客户经理", uRY);
        formMasterData.put("项目经理", uItem);
        formMasterData.put("交付经理", uDelivery);
        formMasterData.put("协作人", xzrValue);
        formMasterData.put("隐-对接-销售订单类型", uSalesOrderType);
        formMasterData.put("所属部门", uBM);
        formMasterData.put("是否梯度价格", data.get("isTDPrice"));
        formMasterData.put("是否例外场景", isLWCJ);
//        formMasterData.put("机会编码", data.get("jhCode"));
//        formMasterData.put("机会名称", data.get("JhName"));
        formMasterData.put("项目行业", itemIndustry);
        formMasterData.put("是否二次定制", isSC);
        formMasterData.put("回款条件", uHKTJ);
        formMasterData.put("天数", data.get("uHKTS"));
        formMasterData.put("总订单数量", data.get("quantity"));
        formMasterData.put("订单状态", orderStatus);
        formMasterData.put("是否阳光彩下单", yEnum.getId());

        //获取明细表数据信息
        double bhszj = 0.0;
        double hszj = 0.0;
        ArrayList<HashMap<String, Object>> subDataLsit = new ArrayList<>();
        ArrayList<HashMap<String, Object>> subDataList = (ArrayList<HashMap<String, Object>>)data.get("mxdataList");
        for (HashMap<String, Object> subData : subDataList) {
            //产品分类
            String productCategory = StrKit.str(subData.get("productCategory"));
            log.info("获取到的产品分类111："+productCategory);
            if(!"".equals(productCategory)){
                CtpEnumItem itemByCode = enumManagerNew.getItemByCode(productCategory);
                if(null != itemByCode){
                    productCategory = itemByCode.getId().toString();
                }
            }
            log.info("获取到的产品分类222："+productCategory);
            //获取税率
            String vatGroup = StrKit.str(subData.get("vatGroup"));
            log.info("获取到的税率1111："+vatGroup);
            String vatGroupCode = "";
            if(!"".equals(vatGroup)){
                CtpEnumItem itemByCode = enumManagerNew.getItemByCode(vatGroup);
                if(null != itemByCode){
                    vatGroup = itemByCode.getId().toString();
                    vatGroupCode = itemByCode.getEnumItemCode();
                }
            }
            log.info("获取到的税率2222："+vatGroup);
            //是否赠品
            String uSFZP = StrKit.str(subData.get("uSFZP"));
            String uSFZPValue = "";
            if(!"".equals(uSFZP)){
                CtpEnumItem itemByCode = enumManagerNew.getItemByCode(uSFZP);
                if(null != itemByCode){
                    uSFZP = itemByCode.getId().toString();
                    uSFZPValue = itemByCode.getShowvalue();
                }
            }

            //转换税率数字 税率-数字-订单明细
            String slsz = slzh(vatGroupCode);

            //计算含税合计
            String slhj = jsHshj(subData,uSFZPValue);
            hszj += Double.parseDouble(slhj);

            //计算不含税单价
            String bhsdj = jsBhsdj(subData,vatGroupCode);

            //不含税合计
            String bhshj = jsBhshj(subData,vatGroupCode,slhj);
            bhszj += Double.parseDouble(bhshj);

            //获取合同数量


            //获取销售订单明细表数据
            HashMap<String, Object> formSubData = new HashMap<>();
            formSubData.put("产品分类-订单明细", productCategory);
            formSubData.put("产品名称-订单明细", subData.get("itemName"));
            formSubData.put("产品编码-订单明细", subData.get("itemCode"));
            formSubData.put("规格型号-订单明细", subData.get("specificationsModels"));
            formSubData.put("计量单位-订单明细", subData.get("measureUnit"));
            formSubData.put("合同数量-订单明细", subData.get("contractNumber"));
            formSubData.put("已下订单数量-订单明细", subData.get("alreadyQuantity"));
            formSubData.put("订单数量-订单明细", subData.get("quantity"));
            formSubData.put("税率-订单明细", vatGroup);   //下拉
            formSubData.put("含税单价-订单明细", subData.get("priceAfterVAT"));
            formSubData.put("税率-数字-订单明细", slsz);
            formSubData.put("含税合计-订单明细", slhj);
            formSubData.put("不含税单价-订单明细", bhsdj);
            formSubData.put("不含税合计-订单明细", bhshj);
            formSubData.put("交货日期-订单明细", data.get("docDueDate"));
            formSubData.put("阶梯价说明-订单明细", subData.get("uExplanationofTieredPricing"));
            formSubData.put("是否赠品-订单明细", uSFZP);
            formSubData.put("备注-订单明细", subData.get("uDocumentLineRemarks"));
            formSubData.put("流水号-订单明细", StrKit.str(UUIDUtil.getUUIDLong()));
            subDataLsit.add(formSubData);
        }

        formMasterData.put("不含税总计", bhszj);
        formMasterData.put("含税总计", hszj);

        //表单字段数据
        HashMap<String, Object> formData = new HashMap<>();
        formData.put(masterTableName,formMasterData);
        formData.put(subTableName,subDataLsit);

        //表单属性
        HashMap<String, Object> formPropertyData = new HashMap<>();
        formPropertyData.put("templateCode", XSDD_TGDD_tempCode);
        formPropertyData.put("draft", "0");
        formPropertyData.put("data", formData);

        //组装发起表单数据
        Map<String,Object> startFormData = new HashMap<>();
        startFormData.put("appName", "collaboration");
        startFormData.put("data", formPropertyData);
        //发起流程表单
        try {
            System.out.println("阳光采发起销售订单数据："+JSONObject.toJSONString(startFormData));
            log.info("阳光采发起销售订单数据："+JSONObject.toJSONString(startFormData));
            HashMap<String, Object> map = FormKit.startForm(startFormData);
            log.info("阳光采发起销售订单返回数据："+JSONObject.toJSONString(map));
            if(!StrKit.str(map.get("code")).equals("200")){
                resulatMap.put("code",map.get("code"));
                resulatMap.put("msg",map.get("msg"));
                resulatMap.put("data",null);
            }else{
                //获取表单流水号数据
                Map<String,Object> dataMap = (Map<String, Object>) map.get("data");
                String app_bussiness_data = StrKit.str(dataMap.get("app_bussiness_data"));
                JSONObject jsonObject = JSONObject.parseObject(app_bussiness_data);
                String affairId = StrKit.str(jsonObject.get("affairId"));

                CtpAffair ctpAffair = affairManager.get(Long.parseLong(affairId));
                Long masterId = ctpAffair.getFormRecordid();
                FormFieldBean djbhFieldBean = formByFormCode.getFieldBeanByDisplay("单据编号");
                FormDataMasterBean dataMasterBeanById = cap4FormManager.getDataMasterBeanById(masterId, formByFormCode, null);
                String djbhValue = StrKit.str(dataMasterBeanById.getFieldValue(djbhFieldBean.getName()));
                HashMap<String, Object> map2 = new HashMap<>();
                map2.put("DocEntry","");
                map2.put("docNum", "");
                map2.put("mxTbhh","");
                map2.put("serialNumber", djbhValue);

                HashMap<String, Object> map1 = new HashMap<>();
                map1.put("isPush", true);
                map1.put("data",map2);
                map1.put("msg", "推送成功");

                resulatMap.put("code",map.get("code"));
                resulatMap.put("msg",map.get("msg"));
                resulatMap.put("data",map1);

            }
        } catch (Exception e) {
            log.error("发起销售订单异常", e);
            resulatMap.put("code",500);
            resulatMap.put("msg","下发销售订单异常");
            resulatMap.put("data",null);
        }
        return resulatMap;
    }


    /**
     * 税率转换
     * @param slCode
     * @return
     */
    private String slzh(String slCode){
        String slsz = "0";
        if(slCode.equals("cg_J1")){
            slsz = "0.01";
        }else if(slCode.equals("cg_J3")){
            slsz = "0.03";
        }else if(slCode.equals("cg_J6")){
            slsz = "0.06";
        }else if(slCode.equals("cg_J9")){
            slsz = "0.09";
        }else if(slCode.equals("cg_J13")){
            slsz = "0.13";
        }

        return slsz;
    }


    /**
     * 计算含税合计
     * @param subData     明细数据
     * @param uSFZPValue  是否赠品枚举显示名称
     * @return
     */
    private String jsHshj(HashMap<String, Object> subData,String uSFZPValue){
        String slhj = "";
        if(uSFZPValue.equals("是")){
            slhj = "0";
        }else{
            String priceAfterVAT = Objects.equals(StrKit.str(subData.get("priceAfterVAT")), "") ? "0" : StrKit.str(subData.get("priceAfterVAT"));
            String quantity = Objects.equals(StrKit.str(subData.get("quantity")), "") ? "0" : StrKit.str(subData.get("quantity"));
            double v = Double.parseDouble(priceAfterVAT) * Double.parseDouble(quantity);
            slhj = String.valueOf(v);
        }
        return slhj;
    }


    /**
     * 计算不含税单价
     * @param subData  明细数据
     * @param slCode   税率枚举编码
     * @return
     */
    private String jsBhsdj(HashMap<String, Object> subData,String slCode){
        String bhshj = "";
        String priceAfterVAT = Objects.equals(StrKit.str(subData.get("priceAfterVAT")), "") ? "0" : StrKit.str(subData.get("priceAfterVAT"));
        if(slCode.equals("cg_J1")){
            double v = Double.parseDouble(priceAfterVAT) / (1 + 0.01);
            bhshj = String.valueOf(v);
        }else if(slCode.equals("cg_J3")){
            double v = Double.parseDouble(priceAfterVAT) / (  1  +  0.03  );
            bhshj = String.valueOf(v);
        }else if(slCode.equals("cg_J6")){
            double v = Double.parseDouble(priceAfterVAT) / (  1  +  0.06  );
            bhshj = String.valueOf(v);
        }else if(slCode.equals("cg_J9")){
            double v = Double.parseDouble(priceAfterVAT) /  (  1  +  0.09  );
            bhshj = String.valueOf(v);
        }else if(slCode.equals("cg_J13")){
            double v = Double.parseDouble(priceAfterVAT)  /  (  1  +  0.13  );
            bhshj = String.valueOf(v);
        }else{
            bhshj = priceAfterVAT;
        }
        return bhshj;
    }


    /**
     * 计算不含税合计
     * @param subData   明细数据
     * @param slCode    明细税率枚举编码
     * @param slhj      明细含税合计
     * @return
     */
    private String jsBhshj(HashMap<String, Object> subData,String slCode,String slhj){
        String bhshj = "";
        String priceAfterVAT = Objects.equals(StrKit.str(subData.get("priceAfterVAT")), "") ? "0" : StrKit.str(subData.get("priceAfterVAT"));
        String quantity = Objects.equals(StrKit.str(subData.get("quantity")), "") ? "0" : StrKit.str(subData.get("quantity"));
        if(slCode.equals("cg_J1")){
            double v = Double.parseDouble(priceAfterVAT) / (1 + 0.01) * Double.parseDouble(quantity);
            bhshj = String.valueOf(v);
        }else if(slCode.equals("cg_J3")){
            double v = Double.parseDouble(priceAfterVAT) / (  1  +  0.03  ) * Double.parseDouble(quantity);
            bhshj = String.valueOf(v);
        }else if(slCode.equals("cg_J6")){
            double v = Double.parseDouble(priceAfterVAT) / (  1  +  0.06  ) * Double.parseDouble(quantity);
            bhshj = String.valueOf(v);
        }else if(slCode.equals("cg_J9")){
            double v = Double.parseDouble(priceAfterVAT) /  (  1  +  0.09  ) * Double.parseDouble(quantity);
            bhshj = String.valueOf(v);
        }else if(slCode.equals("cg_J13")){
            double v = Double.parseDouble(priceAfterVAT)  /  (  1  +  0.13  ) * Double.parseDouble(quantity);
            bhshj = String.valueOf(v);
        }else{
            bhshj = slhj;
        }
        return bhshj;
    }


    /**
     * 保存销售订单数据到档案表中
     * @param data
     * @map ERP返回相关数据
     * @return
     * @throws Exception
     */
    private Boolean saveSalesOrder(Map<String, Object> data,HashMap<String, Object> map) throws Exception {
        //获取填报人信息
        String uCreator = StrKit.str(data.get("uCreator"));
        if(!"".equals(uCreator)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(),
                    "code", uCreator, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uCreator = v3xOrgEntities.get(0).getId().toString();
            }
        }
        //填报部门
        String uDocumentDepartment = StrKit.str(data.get("uDocumentDepartment"));
        if(!"".equals(uDocumentDepartment)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgDepartment.class.getSimpleName(),
                    "code", uDocumentDepartment, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uDocumentDepartment = v3xOrgEntities.get(0).getId().toString();
            }
        }
        //填报单位
        String branchCode = StrKit.str(data.get("branchCode"));
        if(!"".equals(branchCode)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(branchCode);
            if(null != itemByCode){
                branchCode = itemByCode.getId().toString();
            }
        }
        //合同类型
        String contractType = StrKit.str(data.get("contractType"));
        if(!"".equals(contractType)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(contractType);
            if(null != itemByCode){
                contractType = itemByCode.getId().toString();
            }
        }
        //订单类型
        String uSalesOrderBusinessType = StrKit.str(data.get("uSalesOrderBusinessType"));
        if(!"".equals(uSalesOrderBusinessType)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(uSalesOrderBusinessType);
            if(null != itemByCode){
                uSalesOrderBusinessType = itemByCode.getId().toString();
            }
        }
        //客户经理
        String uRY = StrKit.str(data.get("uRY"));
        if(!"".equals(uRY)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(),
                    "code", uRY, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uRY = v3xOrgEntities.get(0).getId().toString();
            }
        }
        //项目经理
        String uItem = StrKit.str(data.get("uItem"));
        if(!"".equals(uItem)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(),
                    "code", uItem, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uItem = v3xOrgEntities.get(0).getId().toString();
            }
        }
        //交付经理
        String uDelivery = StrKit.str(data.get("uDelivery"));
        if(!"".equals(uDelivery)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(),
                    "code", uDelivery, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uDelivery = v3xOrgEntities.get(0).getId().toString();
            }
        }
        //销售主体
        String salesEntity = StrKit.str(data.get("salesEntity"));
        if(!"".equals(salesEntity)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(salesEntity);
            if(null != itemByCode){
                salesEntity = itemByCode.getId().toString();
            }
        }
        //是否二次定制
        String isSC = StrKit.str(data.get("isSC"));
        if(!"".equals(isSC)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(isSC);
            if(null != itemByCode){
                isSC = itemByCode.getId().toString();
            }
        }
        //项目行业
        String itemIndustry = StrKit.str(data.get("itemIndustry"));
        if(!"".equals(itemIndustry)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(itemIndustry);
            if(null != itemByCode){
                itemIndustry = itemByCode.getId().toString();
            }
        }
        //选部门
        String uBM = StrKit.str(data.get("uBM"));
        if(!"".equals(uBM)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgDepartment.class.getSimpleName(),
                    "code", uBM, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uBM = v3xOrgEntities.get(0).getId().toString();
            }
        }
        //订单状态
        String orderStatus = StrKit.str(data.get("orderStatus"));
        if(!"".equals(orderStatus)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(orderStatus);
            if(null != itemByCode){
                orderStatus = itemByCode.getId().toString();
            }
        }

        //协作人
        String uSalesAssistancePersonnel = StrKit.str(data.get("uSalesAssistancePersonnel"));
        String xzrValue = "";
        if(!"".equals(uSalesAssistancePersonnel)){
            String[] split = uSalesAssistancePersonnel.split(",");
            for(int i = 0; i < split.length; i++) {
                List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(),
                        "code", split[i], null, false, true);
                if(!v3xOrgEntities.isEmpty()){
                    xzrValue += v3xOrgEntities.get(0).getId()+",";
                }
            }
            xzrValue = xzrValue.substring(0, xzrValue.length() - 1);
        }


        //是否例外场景
        String isLWCJ = StrKit.str(data.get("isLWCJ"));
        if(!"".equals(isLWCJ)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(isLWCJ);
            if(null != itemByCode){
                isLWCJ = itemByCode.getId().toString();
            }
        }

        //回款条件
        String uHKTJ = StrKit.str(data.get("uHKTJ"));
        if(!"".equals(uHKTJ)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(uHKTJ);
            if(null != itemByCode){
                uHKTJ = itemByCode.getId().toString();
            }
        }

        //获取推送erp数据返回的结果
        Map<String,Object> erpDataMap = (Map<String,Object>)map.get("data");

        //封装主表数据
        HashMap<String, Object> masterData = new HashMap<>();
        masterData.put("单据编号", erpDataMap.get("serialNumber"));
        masterData.put("填报人", uCreator);
        masterData.put("填报部门", uDocumentDepartment);
        masterData.put("填报日期", data.get("docDate"));
        masterData.put("填报单位", branchCode);
        masterData.put("合同名称", data.get("uSalesContractName"));
        masterData.put("合同编号", data.get("uSalesContractNumber"));
        masterData.put("项目名称", data.get("projectName"));
        masterData.put("项目编码", data.get("projectCode"));
        masterData.put("客户名称", data.get("cardName"));
        masterData.put("客户编码", data.get("cardCode"));
        masterData.put("合同类型", contractType);
        masterData.put("订单类型", uSalesOrderBusinessType);
        masterData.put("计划交货日期", data.get("docDueDate"));
        masterData.put("订单金额", data.get("orderPrice"));
        masterData.put("金额大写", data.get("UOrderPrice"));
        masterData.put("订单说明", data.get("comments"));
        masterData.put("ERP单号", erpDataMap.get("docNum"));
        masterData.put("ERP主键", erpDataMap.get("DocEntry"));
        masterData.put("关联报价单", data.get("glbjd"));
        masterData.put("客户经理", uRY);//选人
        masterData.put("项目经理", uItem);//选人
        masterData.put("交付经理", uDelivery);//选人
        masterData.put("已收款金额", data.get("receivableAmount"));
        masterData.put("收款在途金额", data.get("enRouteReceivableAmount"));
        masterData.put("剩余收款金额", data.get("surplusReceivableAmount"));
        masterData.put("ERP单据类型", data.get("ERPReceiptsType"));
        masterData.put("原编码", data.get("rawCode"));
        masterData.put("销售主体", salesEntity);
        masterData.put("是否二次定制", isSC);
        masterData.put("项目行业", itemIndustry);//下拉
        masterData.put("回款条件", uHKTJ);
        masterData.put("天数", data.get("uHKTS"));
        masterData.put("所属部门", uBM);//选部门
        masterData.put("订单状态", orderStatus);

        masterData.put("总订单数量", data.get("orderCount"));
        masterData.put("协作人", xzrValue);//选多人
        masterData.put("是否梯度价格", data.get("isTDPrice"));//下拉
        masterData.put("是否例外场景", isLWCJ);//下拉

        //封装明细数据
        double bhszj = 0.0;
        double hszj = 0.0;
        HashMap<String, List<HashMap<String, Object>>> mxDataMap = new HashMap<>();
        List<HashMap<String, Object>> mxDataList = new ArrayList<>();
        ArrayList<HashMap<String, Object>> subDataList = (ArrayList<HashMap<String, Object>>)data.get("mxdataList");
        for(HashMap<String, Object> subDataMap : subDataList){

            //获取erp行号
            String ERPHH = "";
            List<HashMap<String, Object>> mxTbhhList = (List<HashMap<String, Object>>)erpDataMap.get("mxTbhh");
            log.info("获取到的明细ERP行号："+JSONObject.toJSONString(mxTbhhList));
            for(HashMap<String, Object> mxTbhhMap : mxTbhhList){
                String xNumber = StrKit.str(mxTbhhMap.get("xNumber"));
                if(xNumber.equals(StrKit.str(subDataMap.get("xNumber")))){
                    ERPHH = StrKit.str(mxTbhhMap.get("ERPHH"));
                }
            }

            //获取税率
            String vatGroup = StrKit.str(subDataMap.get("vatGroup"));
            String vatGroupCode = "";
            if(!"".equals(vatGroup)){
                CtpEnumItem itemByCode = enumManagerNew.getItemByCode(vatGroup);
                if(null != itemByCode){
                    vatGroup = itemByCode.getId().toString();
                    vatGroupCode = itemByCode.getEnumItemCode();
                }
            }
            //产品分类
            String productCategory = StrKit.str(subDataMap.get("productCategory"));
            log.info("保存销售订单档案明细-产品分类："+productCategory);
            if(!"".equals(productCategory)){
                CtpEnumItem itemByCode = enumManagerNew.getItemByCode(productCategory);
                if(null != itemByCode){
                    productCategory = itemByCode.getId().toString();
                }
            }
            //是否赠品
            String uSFZP = StrKit.str(subDataMap.get("uSFZP"));
            String uSFZPValue = "";
            if(!"".equals(uSFZP)){
                CtpEnumItem itemByCode = enumManagerNew.getItemByCode(uSFZP);
                if(null != itemByCode){
                    uSFZP = itemByCode.getId().toString();
                    uSFZPValue = itemByCode.getShowvalue();
                }
            }


            //转换税率数字 税率-数字-订单明细
            String slsz = slzh(vatGroupCode);

            //计算含税合计
            String slhj = jsHshj(subDataMap,uSFZPValue);
            hszj += Double.parseDouble(slhj);

            //计算不含税单价
            String bhsdj = jsBhsdj(subDataMap,vatGroupCode);

            //不含税合计
            String bhshj = jsBhshj(subDataMap,vatGroupCode,slhj);
            bhszj += Double.parseDouble(bhshj);

            HashMap<String, Object> subMap = new HashMap<>();
            subMap.put("产品名称-订单明细", subDataMap.get("itemName"));
            subMap.put("产品编码-订单明细", subDataMap.get("itemCode"));
            subMap.put("规格型号-订单明细", subDataMap.get("specificationsModels"));
            subMap.put("合同数量-订单明细", subDataMap.get("contractNumber"));
            subMap.put("历史下单数量-订单明细", subDataMap.get("alreadyQuantity"));
            subMap.put("订单数量-订单明细", subDataMap.get("quantity"));
            subMap.put("计量单位-订单明细", subDataMap.get("measureUnit"));
            subMap.put("税率-订单明细", slsz);
            subMap.put("含税单价-订单明细", subDataMap.get("priceAfterVAT"));
            subMap.put("含税合计-订单明细", slhj);
            subMap.put("阶梯价说明--订单明细", subDataMap.get("uExplanationofTieredPricing"));
            subMap.put("备注-订单明细", subDataMap.get("uDocumentLineRemarks"));
//            subMap.put("ERP单据编号", subDataMap.get(""));
            subMap.put("ERP行号", ERPHH);
            subMap.put("ERP单据行号", ERPHH);
            subMap.put("ERP单据类型-订单明细", 17);
            subMap.put("流水号-订单明细", StrKit.str(UUIDUtil.getUUIDLong()));
            subMap.put("交货日期-订单明细", subDataMap.get("deliveryDate"));
            subMap.put("产品分类-订单明细", productCategory);  //下拉
            subMap.put("是否赠品-订单明细", uSFZP);  //下拉
//            subMap.put("已收款数量-订单明细", subDataMap.get("yskCount"));
            subMap.put("不含税合计-订单明细", bhshj);
            subMap.put("不含税单价-订单明细", bhsdj);
            subMap.put("税率-下拉-订单明细", vatGroup);//下拉
            subMap.put("行号-计算用", subDataMap.get("xNumber"));
            mxDataList.add(subMap);
        }

        masterData.put("含税总计", hszj);
        masterData.put("不含税总计", bhszj);

        mxDataMap.put("订单明细",mxDataList);
        //封装需要保存数据
        HashMap<String, Object> saveDataMap = new HashMap<>();
        saveDataMap.put("masterData",masterData);
        saveDataMap.put("mxData",mxDataMap);

        List<HashMap<String, Object>> mapDataList = new ArrayList<>();
        mapDataList.add(saveDataMap);

        V3xOrgMember seeyonk1 = orgManager.getMemberByLoginName("seeyonk1");
        Boolean aBoolean = FormCap4Kit.saveCAP4FormData(seeyonk1,XSDDDA_temp,mapDataList);
        return aBoolean;
    }


    /**
     * 组装推送SAP数据
     * @param data
     * @return
     */
    private HashMap<String, Object> pushOrderSAP(Map<String, Object> data) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdfS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //同步单号
        String serialNumber = YGC_LSH_QZ + StrKit.str(data.get("serialNumber"));

        HashMap<String, Object> resulatMap = new HashMap<>();
        //获取SAP token信息
        String erp_token = (String) AppContext.getCache("ERP_TOKEN_CQBR");
        if(erp_token.equals("")){
            log.error("获取缓存中erpToken数据为空，请检查dee定时任务获取SAPtoken任务");
            resulatMap.put("isPush",false);
            resulatMap.put("data","");
            return resulatMap;
        }

        //销售订单类型
        String uSalesOrderType = StrKit.str(data.get("uSalesOrderType"));
        if(!"".equals(uSalesOrderType)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(uSalesOrderType);
            if(null != itemByCode){
                uSalesOrderType = itemByCode.getShowvalue();
            }
        }
        //订单类型
        String uSalesOrderBusinessType = StrKit.str(data.get("uSalesOrderBusinessType"));
        if(!"".equals(uSalesOrderBusinessType)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(uSalesOrderBusinessType);
            if(null != itemByCode){
                uSalesOrderBusinessType = itemByCode.getShowvalue();
            }
        }

        //人员
        String uCreator = StrKit.str(data.get("uCreator"));
        if(!"".equals(uCreator)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(),
                    "code", uCreator, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uCreator = v3xOrgEntities.get(0).getCode()+"-"+v3xOrgEntities.get(0).getName();
            }
        }

        //填报部门
        String uDocumentDepartment = StrKit.str(data.get("uDocumentDepartment"));
        if(!"".equals(uDocumentDepartment)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgDepartment.class.getSimpleName(),
                    "code", uDocumentDepartment, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uDocumentDepartment = v3xOrgEntities.get(0).getCode()+"-"+v3xOrgEntities.get(0).getName();
            }
        }

        //协作人
        String uSalesAssistancePersonnel = StrKit.str(data.get("uSalesAssistancePersonnel"));
        String xzrValue = "";
        if(!"".equals(uSalesAssistancePersonnel)){
            String[] split = uSalesAssistancePersonnel.split(",");
            for(int i = 0; i < split.length; i++) {
                List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgMember.class.getSimpleName(),
                        "code", split[i], null, false, true);
                if(!v3xOrgEntities.isEmpty()){
                    xzrValue += v3xOrgEntities.get(0).getCode()+"-"+v3xOrgEntities.get(0).getName()+",";
                }
            }
            xzrValue = xzrValue.substring(0, xzrValue.length() - 1);
        }


        //组装推送SAP 接口数据
        Map<String, Object> dataMap = new HashMap<String, Object>();
        //单据类型
        dataMap.put("DocType", "I");
        //过账日期
        dataMap.put("DocDate", sdf.format(new Date()));
        /*交货日期*/
        dataMap.put("DocDueDate", StrKit.str(data.get("docDueDate")));
        /*客户代码*/
        dataMap.put("CardCode", StrKit.str(data.get("cardCode")));
        /*项目编码*/
        dataMap.put("Project", StrKit.str(data.get("projectCode")));
        /*客户名称*/
        dataMap.put("CardName", StrKit.str(data.get("cardName")));
        /*OA单号*/
        dataMap.put("U_OATBDH", serialNumber);
        /*销售订单类型*/
        dataMap.put("U_SalesOrderType", uSalesOrderType);
        /*销售订单业务类型*/
        dataMap.put("U_SalesOrderBusinessType", uSalesOrderBusinessType);
        /*制单人*/
        dataMap.put("U_Creator", uCreator);
        /*制单时间*/
        dataMap.put("U_DocumentPreparationTime", sdfS.format(new Date()));
        /*制单部门*/
        dataMap.put("U_DocumentDepartment", uDocumentDepartment);
        /*销售协助人员*/
        dataMap.put("U_SalesAssistancePersonnel", xzrValue);
        /*销售合同号*/
        dataMap.put("U_SalesContractNumber", StrKit.str(data.get("uSalesContractNumber")));
        /*人员*/
        dataMap.put("U_RY", uCreator);

        /*部门*/
        String uBM = StrKit.str(data.get("uBM"));
        if(!"".equals(uBM)){
            List<V3xOrgEntity> v3xOrgEntities = orgManager.getEntityList(V3xOrgDepartment.class.getSimpleName(),
                    "code", uBM, null, false, true);
            if(!v3xOrgEntities.isEmpty()){
                uBM = v3xOrgEntities.get(0).getCode()+"-"+v3xOrgEntities.get(0).getName();
            }
        }
        dataMap.put("U_BM", uBM);
        /*我方单位*/
        String branchCode = StrKit.str(data.get("branchCode"));
        if(!"".equals(branchCode)){
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(branchCode);
            if(null != itemByCode){
                branchCode = itemByCode.getShowvalue();
            }
        }
        dataMap.put("U_OurUnit", branchCode);
        /*OA同步时间*/
        dataMap.put("U_OATBSJ", sdfS.format(new Date()));
        /*OA审核时间*/
        dataMap.put("U_OASHSJ", sdfS.format(new Date()));
        /*回款条件*/
        String uHKTJ = StrKit.str(data.get("uHKTJ"));
        if(!uHKTJ.equals("")){
            CtpEnumItem item1 = enumManagerNew.getItemByCode(uHKTJ);
            uHKTJ = item1.getShowvalue();
        }
        dataMap.put("U_HKTJ", uHKTJ);

        /*回款天数*/
        dataMap.put("U_HKTS", StrKit.str(data.get("uHKTS")));
        /*订单说明*/
        dataMap.put("Comments", StrKit.str(data.get("comments")));

        //获取明细表数据
        ArrayList<HashMap<String, Object>> subDataList = (ArrayList<HashMap<String, Object>>)data.get("mxdataList");
        ArrayList<Map<String, Object>> dataList = new ArrayList<>();
        for (HashMap<String, Object> map : subDataList) {
            Map<String, Object> subDataMap = new HashMap<String, Object>();
            /*物料编号*/
            subDataMap.put("ItemCode", StrKit.str(map.get("itemCode")));
            /*OA单据行号*/
            subDataMap.put("U_OATBHH", StrKit.str(map.get("xNumber")));
            /*数量*/
            subDataMap.put("Quantity", StrKit.str(map.get("quantity")));
            /*税率*/
            String VatGroup = StrKit.str(map.get("vatGroup"));
            CtpEnumItem itemByCode = enumManagerNew.getItemByCode(VatGroup);
            if(itemByCode != null){
                //税率转换
                VatGroup = getSlTransition(itemByCode.getShowvalue(),"1");
            }
            subDataMap.put("VatGroup",VatGroup);
            /*折扣后含税单价*/
            subDataMap.put("PriceAfterVAT", StrKit.str(map.get("priceAfterVAT")));
            /*阶梯价说明*/
            subDataMap.put("U_ExplanationofTieredPricing", StrKit.str(map.get("uExplanationofTieredPricing")));

            /*是否赠品*/
            String uSFZP = StrKit.str(map.get("uSFZP"));
            if(!uSFZP.equals("")){
                CtpEnumItem ctpEnumItem = enumManagerNew.getItemByCode(uSFZP);
                uSFZP = ctpEnumItem.getShowvalue();

            }
            subDataMap.put("U_SFZP", uSFZP);

            /*单据备注*/
            subDataMap.put("U_DocumentLineRemarks", StrKit.str(map.get("uDocumentLineRemarks")));

            subDataMap.put("Project", StrKit.str(data.get("projectCode")));
            dataList.add(subDataMap);
        }
        dataMap.put("DocumentLines", dataList);
        String json = JSONObject.toJSONString(dataMap);
        Map<String, Object> headerMap = new LinkedHashMap<String, Object>();
        headerMap.put("Cookie", erp_token);
        log.info("阳光采系统后台直接推送销售订单，推送URL:" + sapOrderUrl + "------销售订单推送json数据：" + json);
        String result = HttpKit.post(sapOrderUrl, headerMap, json);
        if (!result.equals("")) {
            JSONObject jsonObject = JSON.parseObject(result);
            if (jsonObject.containsKey("error")) {
                log.info("阳光采系统后台推送SAP销售订单异常："+result);
                String msg = StrKit.str(jsonObject.getJSONObject("error").getJSONObject("message").get("value"));
                resulatMap.put("isPush",false);
                resulatMap.put("data","");
                resulatMap.put("msg","ERP返回错误信息："+msg);
            } else {
                Map<String, Object> erpMap = new LinkedHashMap<String, Object>();
                String DocEntry = StrKit.str(jsonObject.get("DocEntry"));
                if (!DocEntry.equals("")) {
                    String docNum = StrKit.str(jsonObject.get("DocNum"));
                    ArrayList<Map<String, Object>> mapArraylist = new ArrayList<>();
                    //回写明细行行号
                    List<Map<String, Object>> erpSubList = (List<Map<String, Object>>)jsonObject.get("DocumentLines");
                    for (Map<String, Object> erpSubMap : erpSubList) {
                        String u_oatbhh = StrKit.str(erpSubMap.get("U_OATBHH"));
                        HashMap<String, Object> map = new HashMap<>();
                        map.put("xNumber", u_oatbhh);

                        subDataList.forEach(s -> {
                            String xNumber = StrKit.str(s.get("xNumber"));
                            if (xNumber.equals(StrKit.str(erpSubMap.get("U_OATBHH")))) {
                                map.put("ERPHH", StrKit.str(erpSubMap.get("LineNum")));
                            }
                        });
                        mapArraylist.add(map);
                    }

                    erpMap.put("DocEntry",DocEntry);
                    erpMap.put("docNum", docNum);
                    erpMap.put("mxTbhh",mapArraylist);
                    erpMap.put("serialNumber", serialNumber);
                    resulatMap.put("isPush",true);
                    resulatMap.put("data",erpMap);
                    resulatMap.put("msg","推送成功");

                } else {
                    log.info("阳光采系统后台推送SAP销售订单异常,ERP返回主键为空："+result);
                    resulatMap.put("isPush",false);
                    resulatMap.put("data","");
                    resulatMap.put("msg","推送SAP-ERP失败，返回ERP主键为空！");
                }
            }
        }else{
            log.error("阳光采系统后台直接推送销售订单，SAP接口返回数据为空。返回数据："+result);
            resulatMap.put("isPush",false);
            resulatMap.put("data","");
            resulatMap.put("msg","推送失败,SAP接口返回数据为空。");
        }
        log.error("阳光彩系统后台直接推送销售订单，返回结果："+JSONObject.toJSONString(resulatMap));
        return resulatMap;
    }





    /**
     * 税率转换
     * @param sl       税率值
     * @param type     类型   1 销项【销售】   2 进项 【采购】
     * @return
     */
    private static String getSlTransition(String sl,String type){
        String languahe = "";
        if(sl.equals("0%") && type.equals("1")){
            languahe = "X0";
        }else if(sl.equals("1%") && type.equals("1")){
            languahe = "X1";
        }else if(sl.equals("3%") && type.equals("1")){
            languahe = "X3";
        }else if(sl.equals("6%") && type.equals("1")){
            languahe = "X6";
        }else if(sl.equals("9%") && type.equals("1")){
            languahe = "X9";
        }else if(sl.equals("13%") && type.equals("1")){
            languahe = "X13";
        }else if(sl.equals("0%") && type.equals("2")){
            languahe = "J0";
        }else if(sl.equals("1%") && type.equals("2")){
            languahe = "J1";
        }else if(sl.equals("3%") && type.equals("2")){
            languahe = "J3";
        }else if(sl.equals("6%") && type.equals("2")){
            languahe = "J6";
        }else if(sl.equals("9%") && type.equals("2")){
            languahe = "J9";
        }else if(sl.equals("13%") && type.equals("2")){
            languahe = "J13";
        }else if(sl.equals("J0")){
            languahe = "0%";
        }else if(sl.equals("J1")){
            languahe = "1%";
        }else if(sl.equals("J3")){
            languahe = "3%";
        }else if(sl.equals("J6")){
            languahe = "6%";
        }else if(sl.equals("J9")){
            languahe = "9%";
        }else if(sl.equals("J13")){
            languahe = "13%";
        }else if(sl.equals("X0")){
            languahe = "0%";
        }else if(sl.equals("X1")){
            languahe = "1%";
        }else if(sl.equals("X3")){
            languahe = "3%";
        }else if(sl.equals("X6")){
            languahe = "6%";
        }else if(sl.equals("X9")){
            languahe = "9%";
        }else if(sl.equals("X13")){
            languahe = "13%";
        }
        return languahe;
    }
}
